package com.lotusfall.mysport.controller;

import static android.content.ContentValues.TAG;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Looper;
import android.os.Message;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.lotusfall.mysport.R;
import com.lotusfall.mysport.entity.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UserController {
    User user;
    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    private static final int SUCCESS = 665;
    private static final int FALL = 894;
    public static int flag = 0;
    public static int regular = 0;
    public static String cookie = null;
    public static Long userId = null;
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10,TimeUnit.SECONDS)
            .writeTimeout(10,TimeUnit.SECONDS)
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                    cookieStore.put(httpUrl.host(), list);
                    cookieStore.put(HttpUrl.parse("http://192.168.125.119:8080/").toString(), list);
                    for(Cookie cookie:list){
                        System.out.println("cookie Name:"+cookie.name());
                        System.out.println("cookie Path:"+cookie.path());
                        System.out.println("cookie:"+ cookie);
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                    List<Cookie> cookies = cookieStore.get(httpUrl.host());
                    System.out.println("cookie:"+ cookies);
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            })
            .build();

    public void login(Context context, String username, String password) {
        FormBody formBody= new FormBody.Builder()
                .add("LoginName", username).add("password", password)
                .build();

        Request request= new Request.Builder()
                .post(formBody)
                .url("http://192.168.125.119:8080/login/logUser")
                .build();

        Call call = okHttpClient.newCall(request);


        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)  {
                Looper.prepare();
                String string = null;
                try {
                    string = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Message msg = Message.obtain();
                msg.obj = string;
                msg.what = SUCCESS;
                Log.e("Login:",string);
                //cookie = response.headers("Set-Cookie").get(0);

                List<String> cookies = response.headers().values("Set-Cookie");
                if (cookies.size() > 0) {
                    String session = cookies.get(0);
                    //if (!StringUtils.isNullOrEmpty(session)) {
                        int size = session.length();
                        int i = session.indexOf(";");
                        if (i < size && i >= 0) {
                            //最终获取到的cookie
                            cookie = session.substring(0, i);
                        }
                    //}
                }

                SharedPreferences setting = context.getSharedPreferences("setting", 0);
                setting.edit().putString("cookie", cookie).commit();
                System.out.println("setcookie:"+ cookie);

                if(msg.obj.equals("false")){
                    Toast.makeText(context, "用户名或密码错误！", Toast.LENGTH_SHORT).show();
                    //flag = 0;
                }else if(msg.obj.equals("true")){
                    flag = 1;
                    Toast.makeText(context, "登录成功！", Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Looper.prepare();
                Toast.makeText(context, "请求失败！", Toast.LENGTH_SHORT).show();
                Log.e("Login:","失败！");
                //flag = 0;
                Looper.loop();
            }
        });
    }

    public void reg(Context context, String username, String password) {

        FormBody formBody= new FormBody.Builder()
                .add("LoginName", username).add("password", password)
                .build();

        Request request= new Request.Builder()
                .post(formBody)
                .url("http://192.168.125.119:8080/reg/regUser")
                .build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)  {
                Looper.prepare();
                String string = null;
                try {
                    string = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Message msg = Message.obtain();
                msg.obj = string;
                msg.what = SUCCESS;

                if(msg.obj.equals("false")){
                    Toast.makeText(context, "用户名已存在！请重新输入！！", Toast.LENGTH_SHORT).show();
                    //flag = 0;
                }else if(msg.obj.equals("true")){
                    Toast.makeText(context, "注册成功！", Toast.LENGTH_SHORT).show();
                    regular = 1;
                }
                Looper.loop();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Looper.prepare();
                Toast.makeText(context, "请求失败！", Toast.LENGTH_SHORT).show();
                Log.e("Login:","失败！");
                //flag = 0;
                Looper.loop();
            }
        });
    }


    public void getUserInfo(View view, Activity activity) {
//        SharedPreferences setting = view.getContext().getSharedPreferences("setting", 0);
//        cookie = setting.getString("cookie",cookie);

        TextView stuName = (TextView) view.findViewById(R.id.stu_name);
        TextView stuNum = (TextView) view.findViewById(R.id.stu_num);
        TextView stuKcal = (TextView) view.findViewById(R.id.cal_all);
        TextView stuDist = (TextView) view.findViewById(R.id.dist_all);
        System.out.println("currentCookie" + cookie);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                Request request = new Request.Builder()
                        .get()
                        .url("http://192.168.125.119:8080/getUserInfo")
                        .header("Cookie", cookie)
                        .build();
                try {
                    Response response = okHttpClient.newCall(request).execute(); //获取服务器返回的数据
                    String responseData = response.body().string();
                    JSONArray jsonArray = new JSONArray(responseData);

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Log.e("weather", "run: " + jsonArray);
                                System.out.println("len:" + jsonArray.length());
                                stuNum.setText("账号：" + jsonArray.get(0).toString());
                                stuName.setText("用户名："+jsonArray.get(1).toString());
                                stuKcal.setText(String.format("%.2f", jsonArray.get(2)));
                                stuDist.setText(String.format("%.2f", jsonArray.get(3)));

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            //System.out.println(responseData);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //

            }
        };
        new Thread(runnable).start();
    }
    public void logout() {

    }

}
